package net.huashitong.supervision.appController;

import com.sirdc.modules.core.exceptions.SystemException;
import com.sirdc.modules.core.exceptions.UserExistException;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.*;
import com.sirdc.modules.sys.util.PasswordHelper;
import com.sirdc.modules.sys.util.SysGlobals;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import com.sirdc.modules.utils.date.DateUtils;
import net.huashitong.supervision.task.dataBean.TaskUnitBean;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.CollectFilter;
import net.huashitong.supervision.task.filter.HastenMessageFilter;
import net.huashitong.supervision.task.filter.TaskMainFilter;
import net.huashitong.supervision.task.filter.TaskUnitFilter;
import net.huashitong.supervision.task.service.*;
import net.huashitong.util.DateUtil;
import net.huashitong.util.UtilsTools;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/10/23
 * Time: 15:27
 * To change this template use File | Settings | File Templates.
 * Description:app用户接口controller
 */
@Controller
@RequestMapping(value = "/app/user")
public class UserInfoUtilController extends JsonBaseController {
    @Override
    protected String getView(String s) {
        return null;
    }
    @Autowired
    private AppLoginLogService appLoginLogService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private SysTableService tableService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TaskMainService taskMainService;
    @Autowired
    private TaskUnitService taskUnitService;
    @Autowired
    private TaskUserService taskUserService;
    @Autowired
    private CopeToService copeToService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private HastenMessageService hastenMessageService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private UserManageService userManageService;
    @Autowired
    private PasswordHelper passwordHelper;
    @Autowired
    private ReadDocService readDocService;

    @ResponseBody
    @RequestMapping(value = "/userDateBean")
    public Message userDataBeans(String mobile) {
        if (StringUtils.isNotBlank(mobile)) {
            List<SysUserDataBean> userDataBeans = userService.queryUserDateBeans(mobile);
            Map<String, Object> map = new HashMap<>();
            map.put("systemCode", "DC");
            map.put("systemName", "督查系统");
            map.put("data", userDataBeans);
            return coverMessage("200", "successful", map);
        } else {
            return coverMessage("500");
        }
    }


    /**
     * 首页数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/homeData", method = RequestMethod.POST)
    public Message homeData(@RequestBody SysUserDataBean dataBean) throws UnsupportedEncodingException {



        if (StringUtils.isNotBlank(dataBean.getUsername())) {
            String username = dataBean.getUsername();

            boolean b = sysLoginService.isExistForUsername(username);
            if (!b) {
                return coverMessage("500", "用户已删除");
            }

            int dwc = 0;//待完成条数
            int ywc = 0;//已完成条数
            int zb = 0;//在办条数
            int cb = 0;//未读催办
            int yq = 0; //在办 的逾期
            int thcb = 0; //退回重办

            int deptScore = 0; //得分
            int deptSort = 1;  //排名
            String deptWCL = "0%";
            DecimalFormat df = new DecimalFormat("#.00");

            Map<String, Object> map = new HashMap<>();
            List<Map<String, Object>> xiangzhendwMapList = new ArrayList<>();
            List<Map<String, Object>> xianzhidwMapList = new ArrayList<>();
            //取出登录用户
            SysLogin sysLogin = loginService.getUserByLoginName(username);
            map.put("login", sysLogin);
            if ("10".equals(sysLogin.getRoleId()) || "20".equals(sysLogin.getRoleId())) {
                return coverMessage("200", "200", map);
            }
            String userId = sysLogin.getSysId();
            //全局用户名赋值
            UtilsTools.SysUserName = username;
            UtilsTools.SysUserId = userId;
            SysDept dept = deptService.getById(sysLogin.getDeptId());

            int dcdb = 0;
            int dczb = 0;
            int dcwc = 0;
            if ("/01/".equals(dept.getDeptRelation())) {
                //督查单位
                List<TaskMain> listGjian = new ArrayList<>();
                TaskMainFilter taskMainFilter = new TaskMainFilter();
                taskMainFilter.setAuditorId(null);
                taskMainFilter.setStatus("9");
                taskMainFilter.setInspectionId(dept.getSysId());
                taskMainFilter.setCrucialUser("ZAIBAN");
                //查询攻坚系列
                listGjian = taskMainService.queryFilter(taskMainFilter);
                if ("02".equals(sysLogin.getRoleId())) {
                    //如果是督查主要领导查询当前单位的所有待办事项
                    taskMainFilter = new TaskMainFilter();
                    taskMainFilter.setInspectionId(dept.getSysId());
                    taskMainFilter.setStatus("3");
                    taskMainFilter.setOther("DUCHA");
                    List<TaskMain> taskMains3 = taskMainService.queryFilter(taskMainFilter);
                    taskMainFilter.setStatus("4");
                    taskMainFilter.setOther("");
                    List<TaskMain> taskMains4 = taskMainService.queryFilter(taskMainFilter);
                    dcwc = taskMains4.size();

                    //在办
                    List<TaskMain> unDoneFilter = taskMainService.getUnDoneFilter(taskMainFilter);
                    for (TaskMain taskMain : unDoneFilter) {
                        //在办的所有单位任务
                        List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                        for (TaskUnit taskUnit : taskUnits) {
                            if (taskUnit.getOverdueDay() != null) {
                                yq++;
                            }
                            //退回重办
                            if ("3".equals(taskUnit.getType())) {
                                thcb++;
                            }
                        }
                    }


                    dczb = unDoneFilter.size();
                    //当前单位领导的待审批事项
                    taskMainFilter.setAuditorId(sysLogin.getSysId());
                    taskMainFilter.setStatus("0");
                    List<TaskMain> taskMains1 = taskMainService.queryFilter(taskMainFilter);
                    //查询攻坚派发给单位的未立项的事项
                    if ("/01/".equals(dept.getDeptRelation()) && !dept.getDeptName().startsWith("攻坚")) {
                        //不是攻坚办
                        taskMainFilter.setAuditorId(null);
                        taskMainFilter.setStatus("9");
                        taskMainFilter.setInspectionId(dept.getSysId());
                        taskMainFilter.setCrucialUser("ZAIBAN");
                        //查询攻坚系列
                        listGjian = taskMainService.queryFilter(taskMainFilter);
                    }
                    dcdb = taskMains3.size() + taskMains1.size() + listGjian.size();
                } else {
                    //如果不是只查询自己的待办事项
                    taskMainFilter = new TaskMainFilter();
                    taskMainFilter.setCreateUser(sysLogin.getSysId());
                    taskMainFilter.setStatus("3");
                    taskMainFilter.setOther("DUCHA");
                    List<TaskMain> taskMains3 = taskMainService.queryFilter(taskMainFilter);
                    taskMainFilter.setStatus("4");
                    taskMainFilter.setOther("");

                    List<TaskMain> taskMains4 = taskMainService.queryFilter(taskMainFilter);
                    //在办
                    List<TaskMain> unDoneFilter = taskMainService.getUnDoneFilter(taskMainFilter);

                    for (TaskMain taskMain : unDoneFilter) {
                        //在办的所有单位任务
                        List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                        for (TaskUnit taskUnit : taskUnits) {
                            if (taskUnit.getOverdueDay() != null) {
                                yq++;
                            }
                            //退回重办
                            if ("3".equals(taskUnit.getType())) {
                                thcb++;
                            }
                        }
                    }
                    dczb = unDoneFilter.size();
                    dcwc = taskMains4.size();
                    //当前单位其他人的待审批事项
                    taskMainFilter.setStatus(null);
                    taskMainFilter.setCreateUser(null);
                    taskMainFilter.setAuditorId(sysLogin.getSysId());
                    taskMainFilter.setStatus("0");
                    List<TaskMain> taskMains1 = taskMainService.queryFilter(taskMainFilter);
                    dcdb = taskMains3.size() + taskMains1.size() + listGjian.size();
                }
                if ("/01/".equals(dept.getDeptRelation()) && dept.getDeptName().startsWith("攻坚")) {
                    //攻坚办
                    taskMainFilter = new TaskMainFilter();
                    taskMainFilter.setAuditorId(null);
                    taskMainFilter.setStatus("4");
                    if ("02".equals(sysLogin.getRoleId())) {
                        // 所有的攻坚 主任务 都是领导看的
                        taskMainFilter.setCrucialUser("ALL");
                    } else {
                        taskMainFilter.setCrucialUser(sysLogin.getSysId());
                    }
                    //查询攻坚系列在办
                    List<TaskMain> listZBGjian = taskMainService.getUnDoneFilter(taskMainFilter);
                    //攻坚已完成
                    List<TaskMain> listWCGjian = taskMainService.queryFilter(taskMainFilter);
                    //攻坚待办
                    taskMainFilter.setStatus(null);
                    taskMainFilter.setCrucialState("0");
                    List<TaskMain> listDBGjian = taskMainService.queryFilter(taskMainFilter);
                    dwc = dcdb + listDBGjian.size();
                    zb = dczb + listZBGjian.size();
                    ywc = dcwc + listWCGjian.size();
                } else {
                    zb = dczb;
                    ywc = dcwc;
                    dwc = dcdb;
                }
                HastenMessageFilter hastenMessageFilter = new HastenMessageFilter();
                hastenMessageFilter.setCreateId(userId);
                int size = hastenMessageService.queryFilter(hastenMessageFilter).size();
                cb = size;
            } else {
                //如果不是督查组
                //计算得分和排名


                /*===================================得分情况=======================================*/

                if (dept.getDeptRelation().equals("/02/201/")) {
                    //乡镇
                    List<SysDept> list1 = deptService.queryDeptList("/02/201/");
                    for (SysDept sysDept : list1) {
                        //根据当前单位查询该单位的任务
                        Map<String, Object> map1 = new HashMap<>();
                        TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
                        taskUnitFilter.setDeptId(sysDept.getSysId());
                        taskUnitFilter.setCategoryId("20191022100000000002");
                        //任务数
                        int allSize = taskUnitService.queryByCategory(taskUnitFilter).size();
                        taskUnitFilter.setType("3");
                        //重办数
                        int cbSize = taskUnitService.queryByCategory(taskUnitFilter).size();
                        //已完成数
                        taskUnitFilter.setType("4");
                        List<TaskUnitBean> taskUnitList = taskUnitService.queryByCategory(taskUnitFilter);
                        int ywcSize = taskUnitList.size();
                        //得分
                        int scores = 0;
                        for (TaskUnitBean taskUnit : taskUnitList) {
                            if (StringUtils.isNotBlank(taskUnit.getScore())) {
                                int score = Integer.parseInt(taskUnit.getScore());
                                scores += score;
                            }
                        }
                        //逾期数
                        taskUnitFilter.setType(null);
                        taskUnitFilter.setStatus("10");
                        int yqSize = taskUnitService.queryByCategory(taskUnitFilter).size();
                        //完成率
                        double d = 0;
                        if (ywcSize > 0) {
                            String format = df.format((float) ywcSize / (float) allSize * 100);
                            d = Double.parseDouble(format);
                        }
                        map1.put("allSize", allSize + "");
                        map1.put("cbSize", cbSize + "");
                        map1.put("yqSize", yqSize + "");
                        map1.put("ywcSize", ywcSize + "");
                        map1.put("deptName", sysDept.getDeptName());
                        map1.put("scores", scores);//单位总分
                        map1.put("wcl", d);//单位完成率
                        xianzhidwMapList.add(map1);
                    }
                    if (xiangzhendwMapList != null && xiangzhendwMapList.size() > 1) {
                        Collections.sort(xiangzhendwMapList, new Comparator<Map<String, Object>>() {
                            @Override
                            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                                Double o1Value = Double.valueOf(o1.get("wcl").toString());
                                Double o2Value = Double.valueOf(o2.get("wcl").toString());
                                return o2Value.compareTo(o1Value);
                            }
                        });
                    }
                    //查询当前单位的分数和排名
                    for (int i = 0; i < xiangzhendwMapList.size(); i++) {
                        String deptName = (String) xiangzhendwMapList.get(i).get("deptName");
                        if (dept.getDeptName().equals(deptName)) {
                            deptScore = (int) xiangzhendwMapList.get(i).get("scores");
                            deptWCL = xiangzhendwMapList.get(i).get("wcl") + "";
                            deptSort = i + 1;
                        }
                    }
                } else if (dept.getDeptRelation().equals("/02/202/")) {
                    //县直
                    //如果是县直单位取出说有县直单位
                    List<SysDept> list = deptService.queryDeptList("/02/202/");
                    for (SysDept sysDept : list) {
                        //根据当前单位查询该单位的任务
                        Map<String, Object> map1 = new HashMap<>();
                        TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
                        taskUnitFilter.setCategoryId("20191022100000000002");
                        taskUnitFilter.setDeptId(sysDept.getSysId());
                        //任务数
                        int allSize = taskUnitService.queryByCategory(taskUnitFilter).size();
                        taskUnitFilter.setType("3");
                        //重办数
                        int cbSize = taskUnitService.queryByCategory(taskUnitFilter).size();
                        //已完成数
                        taskUnitFilter.setType("4");
                        List<TaskUnitBean> taskUnitList = taskUnitService.queryByCategory(taskUnitFilter);
                        int ywcSize = taskUnitList.size();
                        //得分
                        int scores = 0;
                        for (TaskUnitBean taskUnit : taskUnitList) {
                            if (StringUtils.isNotBlank(taskUnit.getScore())) {
                                int score = Integer.parseInt(taskUnit.getScore());
                                scores += score;
                            }
                        }
                        //逾期数
                        taskUnitFilter.setType(null);
                        taskUnitFilter.setStatus("10");
                        //完成率
                        double d = 0;
                        if (ywcSize > 0) {
                            String format = df.format((float) ywcSize / (float) allSize * 100);
                            d = Double.parseDouble(format);
                        }
                        int yqSize = taskUnitService.queryByCategory(taskUnitFilter).size();
                        map1.put("allSize", allSize + "");
                        map1.put("cbSize", cbSize + "");
                        map1.put("yqSize", yqSize + "");
                        map1.put("ywcSize", ywcSize + "");
                        map1.put("deptName", sysDept.getDeptName());
                        map1.put("scores", scores);//单位总分
                        map1.put("wcl", d);//单位完成率
                        xianzhidwMapList.add(map1);
                    }
                }

                if (xianzhidwMapList != null && xianzhidwMapList.size() > 1) {
                    Collections.sort(xianzhidwMapList, new Comparator<Map<String, Object>>() {
                        @Override
                        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                            Double o1Value = Double.valueOf(o1.get("wcl").toString());
                            Double o2Value = Double.valueOf(o2.get("wcl").toString());
                            return o2Value.compareTo(o1Value);
                        }
                    });

                }
                //查询当前单位的分数和排名
                for (int i = 0; i < xianzhidwMapList.size(); i++) {
                    String deptName = (String) xianzhidwMapList.get(i).get("deptName");
                    if (dept.getDeptName().equals(deptName)) {
                        deptScore = (int) xianzhidwMapList.get(i).get("scores");
                        deptWCL = xianzhidwMapList.get(i).get("wcl") + "%";
                        deptSort = i + 1;
                    }
                }


                /*===================================得分情况=======================================*/

                if ("02".equals(sysLogin.getRoleId())) {
                    //如果是承办单位领导
                    TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
                    taskUnitFilter.setDeptId(dept.getSysId());

                    List<TaskUnit> unDoneUnit = taskUnitService.getUnDoneUnit(taskUnitFilter);

                    taskUnitFilter.setType("4");
                    List<TaskUnit> doneUnit = taskUnitService.queryFilter(taskUnitFilter);
                    //单位重大事项
                    TaskMainFilter filter = new TaskMainFilter();
                    filter.setOverdueDept(dept.getSysId());
                    //待办单位重大
                    List<TaskMain> overdueDBDeptMain = taskMainService.queryDBOverdueDept(filter);
                    //单位在办督办任务
                    List<TaskMain> overdueZBDeptMain = taskMainService.queryZBOverdueDept(filter);
                    //单位已完成的重大事项
                    List<TaskMain> overdueWCDeptMain = taskMainService.queryWCOverdueDept(filter);
                    ywc = doneUnit.size() + overdueWCDeptMain.size();
                    dwc = unDoneUnit.size() + overdueDBDeptMain.size();
                    //在办
                    List<TaskUnit> nowUnit = taskUnitService.getNowUnit(taskUnitFilter);
                    for (TaskUnit taskUnit : nowUnit) {
                        if (taskUnit.getOverdueDay() != null) {
                            yq++;
                        }
                        //退回重办
                        if ("3".equals(taskUnit.getType())) {
                            thcb++;
                        }
                    }
                    zb = taskUnitService.getNowUnit(taskUnitFilter).size() + overdueZBDeptMain.size();

                } else {
                    //只查看自己的任务
                    TaskUnitFilter filter = new TaskUnitFilter();
                    filter.setUserId(userId);
                    //待办
                    List<TaskUnit> UnDoneUser = taskUnitService.getUnDoneUser(filter);
                    List<TaskUnit> DoneUser = taskUnitService.getDoneUser(filter);
                    //在办
                    List<TaskUnit> nowUser = taskUnitService.getNowUser(filter);
                    zb = taskUnitService.getNowUser(filter).size();
                    for (TaskUnit taskUnit : nowUser) {
                        if (taskUnit.getOverdueDay() != null) {
                            yq++;
                        }
                        //退回重办
                        if ("3".equals(taskUnit.getType())) {
                            thcb++;
                        }
                    }
                    dwc = UnDoneUser.size();
                    ywc = DoneUser.size();
                }
                //未读催办
                HastenMessageFilter hastenMessageFilter = new HastenMessageFilter();
                hastenMessageFilter.setUserId(userId);
                hastenMessageFilter.setStatus("0");
                int size = hastenMessageService.queryFilter(hastenMessageFilter).size();
                cb = size;
            }
            //查询抄送当前用户的待完成个数
            TaskMainFilter filter = new TaskMainFilter();
            filter.setCopeTo(userId);
            List<TaskMain> unDoneCope = copeToService.queryUnDone(filter);
            List<TaskMain> doneCope = copeToService.queryDone(filter);
            dwc += unDoneCope.size();
            ywc += doneCope.size();
//        model.addAttribute("messageCount", messageCount);
//            map.put("login", sysLogin);
            map.put("dept", dept);
            map.put("dwc", dwc);
            map.put("ywc", ywc);
            map.put("zb", zb);
            map.put("cb", cb);
            map.put("yq", yq);
            map.put("thcb", thcb);
            map.put("wcl", deptWCL);   //完成率
            map.put("sort", deptSort); //排名
            map.put("scores", deptScore);//得分

            /*===================记录登录情况==================*/

            AppLoginLog appLoginLog = new AppLoginLog();
            appLoginLog.setDate(DateUtils.getDate());
            appLoginLog.setTime(DateUtils.getTime());
            appLoginLog.setUserId(sysLogin.getSysId());
            appLoginLog.setUserName(sysLogin.getUsername());
            appLoginLog.setDeptId(sysLogin.getDeptId());
            appLoginLog.setDeptName(dept.getDeptName());
            appLoginLog.setRole("01".equals(sysLogin.getRoleId())?"县领导":"02".equals(sysLogin.getRoleId())?"主要领导":"03".equals(sysLogin.getRoleId())?"分管领导":
                    "04".equals(sysLogin.getRoleId())?"经办人":"10".equals(sysLogin.getRoleId())?"县主管":"20".equals(sysLogin.getRoleId())?"管理员":"未知");
            appLoginLog.setRoleId(sysLogin.getRoleId());
            appLoginLogService.save(appLoginLog);

            /*=========================================*/

            return coverMessage("200", "success", map);
        } else {
            return coverMessage("500", "error");
        }

    }

    /**
     * 用户管理
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userManage", method = RequestMethod.POST)
    public Message userManage(@RequestBody SysUserDataBean dataBean) {
        //登录用户单位
        try {
            String deptId = dataBean.getDeptId();
            SysUserFilter filter = new SysUserFilter();
            filter.setDeptId(deptId);
            filter.setName(dataBean.getName());
            List<SysUser> userList = userManageService.getByDeptId(filter);
            return coverMessage("200", "success", userList);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());

        }
    }

    /**
     * 用户管理删除
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public Message deleteUser(@RequestBody SysUserDataBean dataBean) {
        List<String> list = new ArrayList<>();
        list.add(dataBean.getSysId());
        //sysId   要删除的用户id   userId  登录用户的id
        SysUser sysUser = sysUserService.getById(dataBean.getUserId());
        SysUser byId = sysUserService.getById(dataBean.getSysId());
        if ("1".equals(byId.getDemo())) {
            return coverMessage("500", "对不起，您无删除公共账号权限");
        } else if (dataBean.getUserId().equals(dataBean.getSysId())) {
            return coverMessage("500", "删除失败，您不能删除自己");
        } else {
            //公共账号可以删除 自己部门的用户  部门用户不能删除其他成员及公共账号
            sysUserService.batchDelete(list);
            return coverMessage("200", "删除成功");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public Message addUser(@RequestBody SysUserDataBean databean) {
        String userId = databean.getUserId();
        SysLogin userLogin = sysLoginService.getById(userId);
        databean.setUserId(tableService.updateMaxSysId("t_sys_user", null));
        String deptId = userLogin.getDeptId();
        SysDept dept = deptService.getById(deptId);
        String username = databean.getUsername();
        //去空格
        username = username.replace(" ", "");
        //检测用户是否已经存在
        if (sysLoginService.isExistForUsername(username)) {
            if (dept.getDeptName().equals(username)) {
                throw new SystemException(username + "为公共账号，无法添加相同用户名，请重新添加用户");
            }
            //查询当前单位用户是存在该用户
            if (sysLoginService.isExistForUsernameDept(username, deptId)) {
                List<SysLogin> sysLogins = sysLoginService.getByUsernameDept(username, deptId);
                if (ObjectUtils.isNotBlank(sysLogins)) {
                    for (SysLogin sysLogin : sysLogins) {
                        SysUser sysUser = sysUserService.getById(sysLogin.getSysId());
                        if (StringUtils.isNotBlank(databean.getMobile())) {
                            sysUser.setMobile(databean.getMobile());
                        }
                        if (StringUtils.isNotBlank(databean.getPassword())) {
                            sysLogin.setPassword(databean.getPassword());
                            passwordHelper.encryptPassword(sysLogin);
                        }
                        if (StringUtils.isNotBlank(databean.getPosition())) {
                            sysUser.setPosition(databean.getPosition());
                        }
                        if (StringUtils.isNotBlank(databean.getRoleId())) {
                            sysLogin.setRoleId(databean.getRoleId());
                        }
                        sysUser.setState("01");
                        sysLogin.setState("启用");
                        sysLoginService.update(sysLogin);
                        sysUserService.update(sysUser);
                    }
                } else {
//                            return "用户名已存在其他单位: "+lists.get(i).get(0);
                    throw new UserExistException(username);
                }
                return coverMessage("500", "保存失败");
            }
        }

        //保存用户信息
        SysUser user = new SysUser();
        user.setUserId(databean.getUserId());
        user.setSysId(databean.getUserId());
        user.setBirthday(databean.getBirthday());
        user.setDemo(databean.getDemo());
        user.setPosition(databean.getPosition());
        user.setName(databean.getName());
        user.setGender(databean.getGender());
        user.setNativeAddr(databean.getNativeAddr());
        user.setState(SysGlobals.AccountStates.NOMAL);//状态为正常
        user.setIdCard(databean.getIdCard());
        user.setAddress(databean.getEmail());
        user.setMobile(databean.getMobile());
        sysUserService.save(user);

        //保存登陆信息
        SysLogin login = new SysLogin();
        login.setUsername(username);
        if (StringUtils.isNotBlank(databean.getDeptId())) {
            login.setDeptId(databean.getDeptId());
        } else {
            throw new NullPointerException(databean.getDeptId());
        }
        login.setPassword(databean.getPassword());
        login.setRoleId(databean.getRoleId());
        login.setSysId(user.getUserId());
        sysLoginService.save(login);
        return coverMessage("200", "保存成功");
    }

    /**
     * 当前用户详情
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userDetail", method = RequestMethod.POST)
    public Message userDetail(@RequestBody SysUserDataBean datebean) {
        try {
            SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(datebean.getSysId());
            return coverMessage("200", "info", userDataBean);
        } catch (Exception e) {
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 更新用户表操作
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message update(@RequestBody SysUserDataBean datebean) {
        try {
            sysUserService.updateUserLogin(datebean);
            return coverMessage("200", "更新成功");
        } catch (Exception e) {
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 保存收藏
     *
     * @param entity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveCollect", method = RequestMethod.POST)
    public Message saveCollect(@RequestBody CollectEntity entity) {
        try {
            String dateTime = DateUtils.getDateTime();
            entity.setTime(dateTime);
            List<CollectEntity> entities = collectService.getByUserIdAndTaskId(entity.getUserId(), entity.getTaskId(), null);
            if (entities.size() <= 0) {
                collectService.save(entity);
                return coverMessage("200", "收藏成功");
            } else {
                CollectEntity collectEntity = entities.get(0);
                collectEntity.setDel(entity.getDel());
                collectService.update(collectEntity);
                if ("0".equals(entity.getDel())) {
                    return coverMessage("200", "取消收藏成功");
                } else {
                    return coverMessage("200", "收藏成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "失败");
        }
    }

    /**
     * 取消收藏
     *
     * @param entity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delCollect", method = RequestMethod.POST)
    public Message delCollect(@RequestBody CollectEntity entity) {
        if ("0".equals(entity.getDel())) {
            collectService.update(entity);
        }
        return coverMessage("200");
    }

    /**
     * 收藏列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/collectList", method = RequestMethod.POST)
    public Message collectList(@RequestBody CollectFilter filter) {
        List<Object> list = new ArrayList<>();
        List<CollectEntity> collectEntityList = collectService.getByUserIdAndType(filter);
        if (ObjectUtils.isNotBlank(collectEntityList)) {
            for (CollectEntity collectEntity : collectEntityList) {
                if ("10".equals(collectEntity.getType())) {
                    //主任务
                    TaskMain taskMain = taskMainService.getById(collectEntity.getTaskId());
                    list.add(taskMain);
                } else {
                    //单位任务
                    TaskUnit taskUnit = taskUnitService.getById(collectEntity.getTaskId());
                    list.add(taskUnit);
                }
            }
            return coverMessage("200", "收藏列表", list);
        } else {
            return coverMessage("500");
        }
    }

    /**
     * 判断当前任务用户是否收藏过
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "isCollect")
    public Message isCollect(@RequestBody CollectFilter filter) {
        List<CollectEntity> collectEntityList = collectService.getByUserIdAndTaskId(filter.getUserId(), filter.getTaskId(), "1");
        if (collectEntityList.size() <= 0) {
            return coverMessage("200", "未收藏过", false);
        } else {
            return coverMessage("200", "收藏过", true);
        }
    }

    /**
     * 创建呈阅件
     *
     * @param entity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createReadDoc", method = RequestMethod.POST)
    public Message createReadDoc(@RequestBody ReadDocEntity entity) {
        try {
            if (StringUtils.isNotBlank(entity.getSysId())) {
                //修改
                ReadDocEntity byId = readDocService.getById(entity.getSysId());
                readDocService.delete(byId);

            }
            String leaderId = entity.getLeaderId();
            SysUser user = sysUserService.getById(entity.getCreateUserId());
            if (StringUtils.isNotBlank(leaderId)) {
                String[] split = leaderId.split(",");
                for (String s : split) {
                    SysUser leader = sysUserService.getById(s);
                    ReadDocEntity readDocEntity = new ReadDocEntity();
                    BeanUtils.copyProperties(entity, readDocEntity);
                    readDocEntity.setSysId(null);
                    readDocEntity.setCreateUserName(user.getName());
                    readDocEntity.setLeaderName(leader.getName());
                    readDocEntity.setLeaderId(s);
                    readDocService.save(readDocEntity);
                }
                return coverMessage("200", "发送成功");
            } else {
                return coverMessage("500", "发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "发送失败");
        }
    }

    /**
     * 保存呈阅件到草稿箱
     * @param draft
     * @return
     */
    @Autowired
    private ReadDocDraftService readDocDraftService;

    @ResponseBody
    @RequestMapping(value = "/saveReadDocDraft",method = RequestMethod.POST)
    public Message saveReadDocDraft(@RequestBody ReadDocDraft draft){
        if (StringUtils.isNotBlank(draft.getCreateUserId())){
            if (StringUtils.isNotBlank(draft.getTitle())){
                readDocDraftService.save(draft);
                return coverMessage("200","已保存至草稿箱");
            }else {
                return coverMessage("500","无内容,未保存");
            }
        }else {
            return coverMessage("500","无用户");
        }
    }

    /**
     * 当前用户草稿箱
     * @param draft
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "readDocDraftList",method = RequestMethod.POST)
    public Message readDocDraftList(@RequestBody ReadDocDraft draft){
        if (StringUtils.isNotBlank(draft.getCreateUserId())){
            List<ReadDocDraft> list = readDocDraftService.queryList(draft);
            if (ObjectUtils.isNotBlank(list)){
                return coverMessage("200","草稿列表",list);
            }else {
                return coverMessage("500","无草稿");
            }
        }else{
            return coverMessage("500","无用户");
        }
    }
    /**
     * 删除草稿箱内容
     * @param draft
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delDraft",method = RequestMethod.POST)
    public Message delDraft(@RequestBody ReadDocDraft draft){
        if (StringUtils.isNotBlank(draft.getSysId())){
            String[] split = draft.getSysId().split(",");
            ArrayList<String> strings = new ArrayList<>(Arrays.asList(split));
            readDocDraftService.batchDelete(strings);
            return coverMessage("200","删除成功");
        }else {
            return coverMessage("500","删除失败");
        }
    }


    /**
     * 呈阅领导列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryCountyleader", method = RequestMethod.POST)
    public Message queryCountyleader() {
        List<SysLogin> countyLeaderList = sysLoginService.queryCountyleader();
        return coverMessage("200", "200", countyLeaderList);
    }

    /**
     * 我创建的呈阅件列表
     *
     * @param entity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "readDcoList", method = RequestMethod.POST)
    public Message readDocList(@RequestBody ReadDocEntity entity) {
        String createUserId = entity.getCreateUserId();
        List<ReadDocEntity> readDocEntities = readDocService.getByCreateUser(createUserId);
        if (readDocEntities.size() > 0) {
            return coverMessage("200", "success", readDocEntities);
        } else {
            return coverMessage("500", "无数据");
        }
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delReadDoc", method = RequestMethod.POST)
    public Message delReadDoc(@RequestBody ReadDocEntity entity) {
        ReadDocEntity byId = readDocService.getById(entity.getSysId());
        if (ObjectUtils.isBlank(byId)) {
            return coverMessage("500", "500");
        } else {
            if (StringUtils.isNotBlank(byId.getStatus())) {
                return coverMessage("500", "领导已查看,无法删除");
            }
            byId.setDel("0");
            readDocService.update(byId);
            return coverMessage("200", "200");
        }
    }

    /**
     * 用户修改密码
     *
     * @param databean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changePass")
    public Message changePass(@RequestBody SysUserDataBean databean) {
        if (StringUtils.isEmpty(databean.getPassword()) || StringUtils.isEmpty(databean.getOldPassword())) {
            return coverMessage("500", "请输入完整的信息");
        }
        String userId = databean.getUserId();
        SysLogin login = sysUserService.getSysLoginById(userId);
        String encryptPass = sysUserService.getEncryPass(databean.getOldPassword(), login.getSaltKey());
        if (login.getPassword().equals(encryptPass)) {
            databean.setUserId(userId);
            sysUserService.updatePassword(databean);
            return coverMessage("200", "修改成功");
        }
        return coverMessage("500", "对不起，您当前输入的旧密码有误");
    }

    /**
     * 保存 个人基本资料
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveProfile", method = RequestMethod.POST)
    public Message saveProfile(@RequestBody SysUser user) {
        try {
            SysUser sysUser = sysUserService.getById(user.getSysId());
            sysUser.setMobile(user.getMobile());
            sysUser.setName(user.getName());
            sysUserService.update(sysUser);
            return coverMessage("200", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }
}
